package com.sbs.gaoxinqutoilet.activity;

import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.widget.FrameLayout;

import com.sbs.gaoxinqutoilet.R;
import com.sbs.gaoxinqutoilet.base.BaseActivity;
import com.sbs.gaoxinqutoilet.eventbus.EventCenter;
import com.sbs.gaoxinqutoilet.fragment.MainFragment;
import com.sbs.gaoxinqutoilet.http.HttpApis;
import com.sbs.gaoxinqutoilet.http.Request;
import com.sbs.gaoxinqutoilet.interfaces.Constant;
import com.sbs.gaoxinqutoilet.interfaces.EventConstant;
import com.sbs.gaoxinqutoilet.myapp.MyApplication;
import com.sbs.gaoxinqutoilet.receiver.ScreenStatusReceiver;
import com.sbs.gaoxinqutoilet.service.DownLoadService;
import com.sbs.gaoxinqutoilet.service.LoginLinkService;
import com.sbs.gaoxinqutoilet.utils.HttpUtils;
import com.sbs.gaoxinqutoilet.utils.LogUtils;
import com.sbs.gaoxinqutoilet.utils.NetworkUtils;
import com.sbs.gaoxinqutoilet.utils.appinstallerutils.AppUtils;
import com.sibosi.sweetalertlib.SweetAlertDialog;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;

public class MainActivity extends BaseActivity {

    private FrameLayout container;
    private ScreenStatusReceiver screenReceiver;

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
    }

    @Override
    protected void initContentView(Bundle savedInstanceState) {
        setContentView(R.layout.activity_main);


        if (findFragment(MainFragment.class) == null) {
            loadRootFragment(R.id.fl_container, MainFragment.newInstance());
        }
    }

    @Override
    protected void initView() {
        container = (FrameLayout) findViewById(R.id.fl_container);

        EventBus.getDefault().register(this);

    }

    @Override
    protected void initLogic() {
        rquestLoginLink();
        //rquestLoadNewVersion();

    }

    private void rquestLoginLink() {
        //登录服务
        Intent intent = new Intent(this, LoginLinkService.class);
        startService(intent);

        //使用广播间隔登录登录
        screenReceiver = new ScreenStatusReceiver();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(Intent.ACTION_SCREEN_ON); //开屏
        intentFilter.addAction(Intent.ACTION_SCREEN_OFF); //关屏
        registerReceiver(screenReceiver, intentFilter);

    }

    //版本更新
    private void rquestLoadNewVersion() {
        HttpUtils.requestGet(getApplicationContext(), HttpApis.GETVERINFO, new Request() {

            @Override
            public void success(String jsonStr) {
                super.success(jsonStr);
                //获取但前版本
                LogUtils.i("jsonStr", jsonStr);
                try {
                    JSONObject jsonObject = new JSONObject(jsonStr);
                    String versionname = jsonObject.optString("VERSIONNAME");
                    String versioncode = jsonObject.optString("VERSIONCODE");

                    LogUtils.i("mversioninfo", "名" + versionname + " 码" + versioncode);
                    // 获取当前系统的code

                    int appVersionCode = AppUtils.getAppVersionCode(MyApplication.sContext);

                    if (Integer.parseInt(versioncode) > appVersionCode) {
                        //有新版本
                        //判断当前网络
                        if (NetworkUtils.isWifiAvailable(mActivity)) {
                            startDownloadService(versioncode);
                        } else {
                            showDownloadDialog(versioncode);
                        }
                    } else {
                        // 说明当前是最新版本  并且更新成功
                        //那么就删除原来的更新文件
                        String strPath = Environment
                                .getExternalStorageDirectory()
                                .getAbsolutePath() + "/" + "yzd" + appVersionCode + "newCode.apk";
                        final File strFile = new File(strPath);

                        LogUtils.i("strPath", strPath + true);
                        //  如果文件存在
                        if (strFile.exists()) {
                            strFile.delete();
                            Log.e("删除apk", "删除成功");

                        } else {
                            Log.e("删除apk", "已经删除成功");
                            return;
                        }
                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void error(String error) {
                super.error(error);
            }
        });
    }


    private void startDownloadService(String versioncode) {
        Intent intent = new Intent(mActivity, DownLoadService.class);
        intent.putExtra(Constant.VERSION_CODE, versioncode);
        startService(intent);

    }

    private void showDownloadDialog(final String versioncode) {

        final SweetAlertDialog dialog = new SweetAlertDialog(mActivity, SweetAlertDialog.WARNING_TYPE);
        dialog.setTitleText("有新版本").setContentText("您当前处于移动网络,是否下载")
                .setCancelText("取消").setConfirmText("马上下载")
                .setCancelClickListener(null)
                .setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
                    @Override
                    public void onClick(SweetAlertDialog sweetAlertDialog) {
                        startDownloadService(versioncode);
                        dialog.dismiss();
                    }
                }).show();

    }

    @Subscribe
    public void onReceiverEvent(EventCenter center) {
        if (center.getEventCode()== EventConstant.FINISH_MAIN_AC) {
            MainActivity.this.finish();
            LogUtils.i("显示","mainFinish");
        }

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
// TODO: 2018/6/15 两个服务没使用到
//        if (ServiceUtils.isServiceRunning(MainActivity.this, LoginLinkService.class.getName())) {
//            ServiceUtils.stopService(MainActivity.this, LoginLinkService.class.getName());
//        }
        //未执行注册代码
        unregisterReceiver(screenReceiver);
        EventBus.getDefault().unregister(this);
    }
}
